<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="start" style="margin-top: 10px">
        <el-col v-if="currentSystem == 'SysUser'" :span="itemSpan">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" readonly placeholder="请输入项目名称" />
            <el-button
              v-if="currentSystem == 'SysUser'"
              type="primary"
              plain
              style="position: absolute; right: -60px"
              @click="handleSelectProject"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col v-if="!dialogAddOrEdit.id" :span="itemSpan">
          <el-form-item label="参建单位" prop="corpName">
            <el-select v-model="formData.corpName" placeholder="请选择" clearable @change="changeCorp">
              <el-option v-for="item in corps" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan - 2">
          <el-form-item label="姓名" prop="personName">
            <el-input v-model="formData.personName" :disabled="dialogAddOrEdit.id" placeholder="请选择人员" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button v-if="!dialogAddOrEdit.id" type="primary" style="float: right" plain @click="handleSelectPerson"
            >选择</el-button
          >
        </el-col>

        <el-col :span="itemSpan">
          <el-form-item label="证件号码" prop="idCard">
            <el-input v-model="formData.idCard" placeholder="自动获取" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资卡类别" prop="type">
            <el-select v-model="formData.type" placeholder="请选择" clearable>
              <el-option v-for="item in wageTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资卡卡号" prop="cardNo">
            <el-input v-model="formData.cardNo" placeholder="请输入工资卡卡号" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资卡开卡银行" prop="bankName">
            <el-select v-model="formData.bankName" filterable placeholder="请选择" clearable>
              <el-option v-for="item in bankTypeTypes" :key="item.label" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <select-project :dialog-select="dialogSelectProject" @select-send-close="projectSendClose"></select-project>
      <select-person :dialog-select="dialogSelectPerson" @select-send-close="personSendClose"></select-person>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { addPersonBank, editPersonBank, getPersonBankInfo } from "@/api/wage/index";
import { PersonBankEditForm } from "@/api/wage/types";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import SelectProject from "@/views/common/SelectProject/index.vue";
import SelectPerson from "@/views/common/SelectPerson/index.vue";
import { getProjectCorps } from "@/api/group/index";

const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor"));
//工资卡类型
const wageTypes = getDicts("personCardType");
const bankTypeTypes = getDicts("bankTypeTypes");
// 参建单位列表（需要从API获取）
const corps = ref();

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
      corpId: 0,
    }),
  },
});

const { dialogAddOrEdit } = toRefs(props);

const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<PersonBankEditForm>({
  bankName: "西藏银行股份有限公司",
  type: 2,
  isDefault: true,
});
const addOrEditFormRef = ref(ElForm);

const dialogSelectProject = reactive({
  visible: false,
  title: "选择项目",
  footBtn: "确认",
  id: 0,
  type: "allproject",
});
const handleSelectProject = function () {
  dialogSelectProject.visible = true;
};
const projectSendClose = function (info: any) {
  dialogSelectProject.visible = false;
  if (info) {
    formData.projectId = info.projectId;
    formData.projectName = info.projectName;
    formData.corpName = undefined;
    formData.corpId = undefined;
  }
};

const dialogSelectPerson = reactive({
  visible: false,
  title: "选择人员",
  footBtn: "确认",
  id: 0,
  corpId: 0,
});
const handleSelectPerson = function () {
  if (formData.corpId == undefined || formData.corpId == 0) {
    ElMessage.warning("请选择企业");
    return;
  }
  dialogSelectPerson.corpId = formData.corpId;
  dialogSelectPerson.visible = true;
};
const personSendClose = function (info: any) {
  dialogSelectPerson.visible = false;
  if (info) {
    formData.personId = info.personId;
    formData.personName = info.name;
    formData.idCard = info.cardNumber;
  }
};

//改变选择单位回调
const changeCorp = function (val: any) {
  let temp = corps.value.filter((item: { value: string }) => item.value == val);
  console.log(val);
  console.log(temp);
  if (temp.length > 0) {
    formData.corpId = temp[0].value;
    formData.corpName = temp[0].label;
    formData.personName = undefined;
    formData.personId = undefined;
    formData.idCard = undefined;
    return;
  }
};

//表单验证规则
const rules = reactive<FormRules<PersonBankEditForm>>({
  corpName: [{ required: true, message: "请选择企业", trigger: "blur" }],
  personName: [{ required: true, message: "请选择人员", trigger: "blur" }],
  type: [{ required: true, message: "请选择工资卡类型", trigger: "blur" }],
  cardNo: [
    { required: true, message: "请输入工资卡卡号", trigger: "blur" },
    {
      trigger: "blur",
      message: "银行卡卡号仅允许16-19位数字",
      validator: (rule: any, value: string) => {
        return /^[0-9]{16,19}$/.test(value);
      },
    },
  ],
  bankName: [{ required: true, message: "请输入工资卡开卡银行", trigger: "blur" }],
  isDefault: [{ required: true, message: "请选择是否默认", trigger: "blur" }],
});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}

const initCorps = async function () {
  let res = await getProjectCorps();
  if (res.type === 0) {
    if (res.success) {
      corps.value = res.data;
    } else {
    }
  } else {
  }
};
if (currentSystem.value != "SysUser") {
  initCorps();
}

const initForm = async function () {
  if (dialogAddOrEdit.value.id) {
    loading.value = true;
    let res = await getPersonBankInfo(dialogAddOrEdit.value.id, dialogAddOrEdit.value.corpId);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        Object.assign(formData, res.data);
      } else {
      }
    } else {
    }
  }
};

watch(
  () => dialogAddOrEdit.value.visible,
  () => {
    if (dialogAddOrEdit.value.visible) {
      initForm();
    }
  }
);
onMounted(async () => {
  initScreen();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.projectId = undefined;
  formData.corpId = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (dialogAddOrEdit.value.id || dialogAddOrEdit.value.id > 0) {
        editPersonBank(dialogAddOrEdit.value.id, formData)
          .then((res) => {
            if (res.type === 0) {
              if (res.success === true) {
                ElMessage.success(res.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(res.msg);
              }
            } else {
              ElMessage.warning(res.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      } else {
        addPersonBank(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
